from paho.mqtt import client as mqtt_client
import configparser
import logging
import time
from paho.mqtt.client import MQTTv5

topic = "audio/report"
# username = 'web'
# password = '123456'

FIRST_RECONNECT_DELAY = 1
RECONNECT_RATE = 2
MAX_RECONNECT_COUNT = 12
MAX_RECONNECT_DELAY = 60

config = configparser.ConfigParser()
config.read("config.ini", encoding="utf-8")

broker = config.get("mqtt", "broker")
port = config.getint("mqtt", "port")

user_name = config.get("mqtt", "user")
pass_word = config.get("mqtt", "pass")

def on_connect(client, userdata, flags, rc, properties=None):
    if rc == 0 and client.is_connected():
        print("Connected to MQTT Broker!")
    else:
        print(f'Failed to connect, return code {rc}')


def on_disconnect(client, userdata, rc, properties=None):
    logging.info("Disconnected with result code: %s", rc)
    reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAY
    while reconnect_count < MAX_RECONNECT_COUNT:
        logging.info("Reconnecting in %d seconds...", reconnect_delay)
        time.sleep(reconnect_delay)
        try:
            client.reconnect()
            logging.info("Reconnected successfully!")
            return
        except Exception as err:
            logging.error("%s. Reconnect failed. Retrying...", err)

        reconnect_delay *= RECONNECT_RATE
        reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)
        reconnect_count += 1
    logging.info("Reconnect failed after %s attempts. Exiting...", reconnect_count)
    global FLAG_EXIT
    FLAG_EXIT = True


def connect_mqtt(CLIENT_ID):
    # client = mqtt_client.Client(CLIENT_ID)
    client = mqtt_client.Client(client_id=CLIENT_ID, protocol=MQTTv5)
    client.username_pw_set(user_name, pass_word)
    client.on_connect = on_connect
    client.connect(broker, port, keepalive=30)
    client.on_disconnect = on_disconnect
    return client


def publish(client,msg):
    print(client.is_connected())
    if not client.is_connected():
        return
    result = client.publish(topic, msg)
    # result: [0, 1]
    status = result[0]
    if status == 0:
        print(f'Send `{msg}` to topic `{topic}`')
    else:
        print(f'Failed to send message to topic {topic}')

